import {createStore} from "vuex";
import {ref} from "vue";
import Api from "@/api/user"

const store = createStore(
    {
        state: {
            user: {
                online: false,
                nickname: '',
                avatar: 'unsigned.png',
                usertype: '',
                isDark: ref(false),
            },
            search: {
                key: ''
            }
        },
        getters: {
            avatar: state => state.user.avatar,
            online: state => state.user.online,
            usertype: state => state.user.usertype,
            nickname: state => state.user.nickname
        },
        actions: {
            getUserInfo({commit, state}) {
                return new Promise((resolve, reject) => {
                    Api.getInfo().then(res => {
                        commit('SET_NICKNAME', res.data.data.nickName);
                        commit('SET_AVATAR', res.data.data.avatar);
                        commit('SET_USERTYPE', res.data.data.userType);
                        resolve(res)
                    }).catch(error => {
                        reject(error);
                    })
                })
            }
        },
        mutations: {
            SET_NICKNAME(state, nickname) {
                state.user.nickname = nickname;
            },
            SET_AVATAR(state, avatar) {
                state.user.avatar = avatar;
            },
            SET_USERTYPE(state, usertype) {
                state.user.usertype = usertype;
            },
            changeIsDark(state) {
                state.user.isDark = !state.user.isDark;
            },
            changeOnlineStatus(state) {
                state.user.online = !state.user.online;
            },
            SET_KEY(state, key) {
                state.search.key = key;
            }
        }
    }
)
export default store
